package beer.coder.walawala.common.logger;

import java.io.File;
import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 日志工具.
 *
 * @author amath0312
 * @version 1.0
 * @date 2020-04-19 11:18
 */
public class Log {

  private static Logger logger = Logger.getAnonymousLogger();
  private static FileHandler fileHandler;
  private static ConsoleHandler consoleHandler;

  static {
    logger.setLevel(Level.ALL);

    consoleHandler = new ConsoleHandler();
    consoleHandler.setLevel(logger.getLevel());
    consoleHandler.setFormatter(new LogFormatter());
    logger.addHandler(consoleHandler);
  }

  public static void enableFileHandler() {
    if (fileHandler == null) {
      try {
        fileHandler = new FileHandler(new File(System.getProperty("user.dir"), "wa.log").getAbsolutePath(),
            true);
        fileHandler.setFormatter(new LogFormatter());
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    if (fileHandler != null) {
      fileHandler.setLevel(logger.getLevel());
      logger.addHandler(fileHandler);
    }
  }

  public static void disableFileHandler() {
    if (fileHandler != null) {
      logger.removeHandler(fileHandler);
    }
  }

  public static void setLevel(Level level) {
    if (logger != null) {
      logger.setLevel(level);
    }
    if (fileHandler != null) {
      fileHandler.setLevel(level);
    }
    if (consoleHandler != null) {
      consoleHandler.setLevel(level);
    }
  }

  public static void d(String tag, String message) {
    logger.fine(tag + " | " + message);
  }

  public static void d(String tag, String format, Object... params) {
    d(tag, String.format(format, params));
  }

  public static void w(String tag, String message) {
    logger.warning(tag + " | " + message);
  }

  public static void w(String tag, String format, Object... params) {
    w(tag, String.format(format, params));
  }

  public static void e(String tag, String message) {
    logger.severe(tag + " | " + message);
  }

  public static void e(String tag, String format, Object... params) {
    e(tag, String.format(format, params));
  }

  public static void e(String tag, String message, Throwable e) {
    logger.log(Level.SEVERE, tag + " | " + message, e);
  }

}
